<?php
import("ORG.Util.Function");
import("@.ORG.Utils");
import("@.ORG.GoodscatTool"); /*分类处理工具类*/


class GoodscatAction extends CommonAction{	
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	public function _empty(){
		t('空操作');
	}
	
	// 分类列表
	public function cat_list(){		
		$GoodsCatModel	=	new GoodsCatModel();
		$catList		=	$GoodsCatModel->getCategoryList();
		$this->assign("catList",$catList);
		$this->display();
	}
	
	/** 
	 * 添加分类
	 * 
	 */
	public function add_cat(){	
		/*商品分类*/ 	
		$GoodsCatModel	=	new GoodsCatModel();
		$goodsCatList	=	$GoodsCatModel->getCategoryList();
		/*商品类型*/ 
		$TypeModel		=	new TypeModel();
		$goodsTypeList	=	$TypeModel->getTypeList();
		/*商品属性*/
		
		
		$this->assign("attr_list",get_attr_list());
		
		
		$this->assign("goodsCatList",$goodsCatList);	/*商品分类*/ 
		$this->assign("goodsTypeList",$goodsTypeList);	/*商品类型*/ 
		$this->display();
	}
	
	// 处理添加分类
	public function add_cat_ok(){
	    // 初始化变量
	    $cat['parent_id']    = !empty($_POST['parent_id'])    ? intval($_POST['parent_id'])  : 0;
	    $cat['sort_order']   = !empty($_POST['sort_order'])   ? intval($_POST['sort_order']) : 0;
	    $cat['keywords']     = !empty($_POST['keywords'])     ? trim($_POST['keywords'])     : '';
	    $cat['cat_desc']     = !empty($_POST['cat_desc'])     ? $_POST['cat_desc']           : '';
	    $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : '';
	    $cat['cat_name']     = !empty($_POST['cat_name'])     ? trim($_POST['cat_name'])     : '';
	    $cat['show_in_nav']  = !empty($_POST['show_in_nav'])  ? intval($_POST['show_in_nav']): 0;
	    $cat['style']        = !empty($_POST['style'])        ? trim($_POST['style'])        : '';
	    $cat['is_show']      = !empty($_POST['is_show'])      ? intval($_POST['is_show'])    : 0;
	    $cat['grade']        = !empty($_POST['grade'])        ? intval($_POST['grade'])      : 0;
	    $cat['filter_attr']  = !empty($_POST['filter_attr'])  ? implode(',', array_unique(array_diff($_POST['filter_attr'],array(0)))) : 0;
		
	    // 是否设为首页推荐
	    $cat_recommend		 = !empty($_POST['cat_recommend'])  ? $_POST['cat_recommend'] : array();
	    	    
	    if (Utils::cat_exists($cat['cat_name'], $cat['parent_id']))
	    {
	        // 同级别下不能有重复的分类名称
	    	$this->error("同级别下不能有重复的分类名称 ",U("goodscat/add_cat"));
	    }
	
//	    if($cat['grade'] > 10 || $cat['grade'] < 0)
//	    {
//	        /* 价格区间数超过范围 */
//	       $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
//	       sys_msg($_LANG['grade_error'], 0, $link);
//	    }
	
	    // 入库的操作
	    $GoodsCatModel	=	new GoodsCatModel();
	    $NavModel		=	M("Nav");
	    $id				=	$GoodsCatModel->addGoodsCategory($cat);
	    
	    t($id);
	    
	    if($id){
	    	$vieworder	=	M('Nav')->field("max(vieworder) vieworder")->find();
			// 插入后,显示不显示在导航栏中
	     	if($cat['show_in_nav'] == 1){	     			     		
	     		$vieworder['vieworder']	.=	2;	// 修改顺序
	     		
	     		$datas['name']			=	$cat['cat_name'];
	     		$datas['ctype']			=	'c';
	     		$datas['cid']			=	$id;
	     		$datas['ifshow']		=	1;
	     		$datas['vieworder']		=	$vieworder['vieworder'];
	     		$datas['opennew']		=	0;
	     		//$datas['url']			=	U('goodscat/');  // 写一个函数专门生成URL
	     		$datas['type']			=	'middle';
	     		$id 					= 	$NavModel->add($datas);
	     		t($id);
	        }
	        // 首页推荐表
	        $this->success("操作成功,正在为您跳转",U('goodscat/add_cat'));
	    }
	}
	
	// 删除分类
	public function del_cat(){					
		$cat_id   			= 	intval($_REQUEST['id']);
		
		$return_msg			=	array(
			'data'	=> 0,
			'info'	=> '操作失败',
			'status'=> 0
		);
		
		$GoodsCatModel		=	new GoodsCatModel();
		$cat_name			=	$GoodsCatModel->getCatNameById($cat_id);
		// 当前分类下是否有子分类 		
		$cat_count			=	$GoodsCatModel->getChildCount($cat_id);
	    // 当前分类下是否存在商品 
	    $goods_count 		= 	$GoodsCatModel->getGoodsByCatId($cat_id);
	    
	    // 如果不存在下级子分类和商品，则删除之
	    if ($cat_count == 0 && $goods_count == 0){
	        // 删除分类	      
	        if( M('Category')->where("cat_id = {$cat_id}")->delete() ){
	        	M('Nav')->where(" cid= {$cat_id} and ctype='c' and type='middle' ")->delete();
	        	//$this->error("操作成功,正在为您跳转...",U("goodscat/cat_list"));
	        	$return_msg['data']	=	1;	
	        	$return_msg['info']	=	'操作成功';	
	        	$return_msg['staus']=	1;	
	        }
	    }
	    else
	    {
	        //$this->error("操作失败,正在为您跳转...",U("goodscat/cat_list"));
	        $return_msg['data']	=	0;	
        	$return_msg['info']	=	'该分类下存在子分类';	
        	$return_msg['staus']=	1;	
	    }

	    if($this->isAjax()){
	    	/*isAjax*/
	    	$this->ajaxReturn($return_msg);
	    }
	    else{
	    	if($return_msg['data'] == 1){
	    		$this->success($return_msg['info'],U('goodscat/cat_list'));
	    	}
	    	else{
	    		$this->error($return_msg['info'],U('goodscat/cat_list'));
	    	}
	    }
	}
	
	// 修改分类 [undo]
	public function mod_cat(){
		
		$CommonModel		=	new CommonModel();
		$GoodsCatModel		=	new GoodsCatModel();
		
	    $cat_id 			= 	intval($_REQUEST['id']);
	    $cat_info 			= 	get_cat_info($cat_id);  // 查询分类信息数据
	    $attr_list 			= 	get_attr_list();
	    $filter_attr_list 	= 	array();
	
	    if ($cat_info['filter_attr']){
	        $filter_attr 	= 	explode(",", $cat_info['filter_attr']);  //把多个筛选属性放到数组中
	
	        foreach ($filter_attr AS $k => $v){
	            $attr_cat_id 								= 	$CommonModel->getOne("SELECT cat_id FROM " . 'ybr_attribute' . " WHERE attr_id = '" . intval($v) . "'");
	            $filter_attr_list[$k]['goods_type_list'] 	= 	goods_type_list($attr_cat_id);  //取得每个属性的商品类型
	            //t(goods_type_list($attr_cat_id));
	            $filter_attr_list[$k]['filter_attr']	 	= 	$v;
	            $attr_option 								= 	array();
	
	            foreach ($attr_list[$attr_cat_id] as $val){
	                $attr_option[key($val)] 				= 	current ($val);
	            }
	
	            $filter_attr_list[$k]['option'] = $attr_option;
	        }
	
	        $this->assign('filter_attr_list', $filter_attr_list);
	    }
	    else{
	        $attr_cat_id 			= 	0;
	    }
	
	    /* 模板赋值 */
	    $this->assign('attr_list',        $attr_list); // 取得商品属性
	    $this->assign('attr_cat_id',      $attr_cat_id);
	
	    //分类是否存在首页推荐
	    $res 				= 	M()->query("SELECT recommend_type FROM " . " ybr_cat_recommend" . " WHERE cat_id=" . $cat_id);
	    if (!empty($res)){
	        $cat_recommend 	=	array();
	        foreach($res as $data){
	            $cat_recommend[$data['recommend_type']] 	= 	1;
	        }
	        $this->assign('cat_recommend', $cat_recommend);
	    }
	    
	    //t($filter_attr_list);
	    //t($GLOBALS['_CFG']['is_leaf_error']);
	    
	    $this->assign('cat_info',    $cat_info);
	    $this->assign('form_act',    'update');
	    $this->assign('cat_select',  $cat_info['parent_id']);
	    $this->assign('cat_id',  $cat_id);
	    $this->assign('goods_type_list',  goods_type_list($cat_info['parent_id'])); // 取得商品类型	    
	    $this->assign('goodsCatList',  $GoodsCatModel->getCategoryList()); // 取得商品分类
		/* 显示页面 */
	    //t(goods_type_list($cat_info['parent_id']));
	    //t($GoodsCatModel->getCategoryList());	
		$this->display();
	}

	/**
	 * 处理修改分类信息
	 * 
	 */
	public function mod_cat_ok(){
		/*构造数组*/
	    $cat_id              = !empty($_POST['cat_id'])       ? intval($_POST['cat_id'])     : 0;
	    $old_cat_name        = $_POST['old_cat_name'];
	    $cat['parent_id']    = !empty($_POST['parent_id'])    ? intval($_POST['parent_id'])  : 0;
	    $cat['sort_order']   = !empty($_POST['sort_order'])   ? intval($_POST['sort_order']) : 0;
	    $cat['keywords']     = !empty($_POST['keywords'])     ? trim($_POST['keywords'])     : '';
	    $cat['cat_desc']     = !empty($_POST['cat_desc'])     ? $_POST['cat_desc']           : '';
	    $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : '';
	    $cat['cat_name']     = !empty($_POST['cat_name'])     ? trim($_POST['cat_name'])     : '';
	    $cat['is_show']      = !empty($_POST['is_show'])      ? intval($_POST['is_show'])    : 0;
	    $cat['show_in_nav']  = !empty($_POST['show_in_nav'])  ? intval($_POST['show_in_nav']): 0;
	    $cat['style']        = !empty($_POST['style'])        ? trim($_POST['style'])        : '';
	    $cat['grade']        = !empty($_POST['grade'])        ? intval($_POST['grade'])      : 0;
	    $cat['filter_attr']  = !empty($_POST['filter_attr'])  ? implode(',', array_unique(array_diff($_POST['filter_attr'],array(0)))) : 0;
	    $cat['cat_recommend']  = !empty($_POST['cat_recommend'])  ? $_POST['cat_recommend'] : array();
		
	    $CommonModel		=	new CommonModel();
	    
	    /* 判断分类名是否改变 */	
	    if ($cat['cat_name'] != $old_cat_name){
	        if (cat_exists($cat['cat_name'],$cat['parent_id'], $cat_id)){
	           $this->error("分类名已经存在");
	        }
	    }
	
	    /*判断父分类是否在该分类下的子分类,子分类不能作为它的父分类*/
	    $children = array_keys(cat_list($cat_id, 0, false));   
	    if (in_array($cat['parent_id'], $children)){
	       $this->error("该分类是当前分类下的子分类,不能作为该类的父分类");
	    }
	    /*if($cat['grade'] > 10 || $cat['grade'] < 0){
	    	//sys_msg($_LANG['grade_error'], 0, $link);
	    	$this->error("价格分级不在规定的范围内 ： 0-10");
	    }*/
	
	    $dat 		= 	$CommonModel->getRow("SELECT cat_name, show_in_nav FROM ". 'ybr_category' . " WHERE cat_id = '$cat_id'");
	
	    if ($CommonModel->autoExecute('category', $cat, 'UPDATE', "cat_id='$cat_id'")){
	        if($cat['cat_name'] != $dat['cat_name']){
	            /*分类名不一致,则更新*/
	        	$sql 	= 	"UPDATE " . 'ybr_nav' . " SET name = '" . $cat['cat_name'] . "' WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'";
	            M()->query($sql);
	        }
	        if($cat['show_in_nav'] != $dat['show_in_nav']){
	            /*是否显示在导航栏*/
	            if($cat['show_in_nav'] == 1){
	                //
	                $nid = $CommonModel->getOne("SELECT id FROM ". 'ybr_nav' . " WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'");
	                if(empty($nid)){
	                    //
	                    $vieworder	 	= 	$CommonModel->getOne("SELECT max(vieworder) FROM ". 'ybr_nav' . " WHERE type = 'middle'");
	                    $vieworder 		+= 	2;
	                    
	                    $sql 			= 	"INSERT INTO " . 'ybr_nav' . " (name,ctype,cid,ifshow,vieworder,opennew,url,type) VALUES('" . $cat['cat_name'] . "', 'c', '$cat_id','1','$vieworder','0', '" . $uri . "','middle')";
	                }
	                else{
	                    $sql 			= 	"UPDATE " . 'ybr_nav' . " SET ifshow = 1 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'";
	                }
	                $CommonModel->execute($sql);
	            }
	            else{                
	                M()->execute("UPDATE " . 'ybr_nav' . " SET ifshow = 0 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'");
	            }
	        }
	        /*插入数据*/
	        insert_cat_recommend($cat['cat_recommend'], $cat_id);
	        admin_log($_POST['cat_name'], 'edit', 'category'); 
	    }	    
	   	$this->success('操作成功',U('Goodscat/cat_list'));
	}
	
	// 转移商品分类[undo]
	public  function move_cat(){
		
		$this->display();
	}
	
	/**
	 * 获取商品类型的属性
	 * 
	 */
	public function get_goodstype_attr(){
		
		$cat_id	=	intval($_POST['cat_id']);
		if(empty($cat_id)){
			$this->ajaxReturn(1,"",1);
		}		
		$sql 	= 	"SELECT a.attr_id, a.cat_id, a.attr_name ".
	           		" FROM " . 'ybr_attribute'. " AS a,  ".
	           		'ybr_goods_type' . " AS c ".
	           		" WHERE  a.cat_id = c.cat_id AND c.enabled = 1 and c.cat_id='{$cat_id}' ".
	           		" ORDER BY a.cat_id , a.sort_order";
		$attr_list	=	M()->query($sql);
		
		if($this->isAjax()){
			$template	=	"Goodscat:l_attr_list";
			$this->assign("attr_list",$attr_list);
			$html		=	$this->fetch($template);	
			$this->ajaxReturn(1,$html,1);	
		}
		return $attr_list;
	}
	
}





